package com.mlink.vs.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.seasar.struts.annotation.Execute;

import com.google.gson.Gson;
import com.mlink.vs.entity.BaiduAddPointResult;
import com.mlink.vs.entity.PiccUser;
import com.mlink.vs.entity.PiccUserArea;
import com.mlink.vs.entity.PiccUserLocation;
import com.mlink.vs.entity.UCResult;
import com.mlink.vs.service.DbTimeService;
import com.mlink.vs.service.PiccTaskFileService;
import com.mlink.vs.service.PiccTaskPoolService;
import com.mlink.vs.service.PiccTaskStatusService;
import com.mlink.vs.service.PiccUserAreaService;
import com.mlink.vs.service.PiccUserLocationService;
import com.mlink.vs.service.PiccUserService;
import com.mlink.vs.sso.BaseAction;
import com.mlink.vs.util.Constants;
import com.mlink.vs.util.StreamUtil;

public class UserAction extends BaseAction {

	/**
	 * request请求对象
	 */
	@Resource
	private HttpServletRequest req;

	/**
	 * response请求对象
	 */
	@Resource
	private HttpServletResponse rep;

	@Resource
	PiccUserService piccUserService;

	@Resource
	PiccTaskPoolService piccTaskPoolService;

	@Resource
	PiccTaskStatusService piccTaskStatusService;

	@Resource
	private PiccTaskFileService piccTaskFileService;

	@Resource
	private PiccUserAreaService piccUserAreaService;

	@Resource
	private PiccUserLocationService piccUserLocationService;

	@Resource
	DbTimeService dbTimeService;

	// 获取用户信息接口
	@Execute(validator = false)
	public String fetchUserInfo() {

		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);

		Map<String, String> stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;
		// token验证不成功，退出
		if (BaseAction.checkToken(indata, rep) == false)
			return null; // 验证token是否有效 无效直接返回错误码-1000

		String userId = (String) mapData.get("userId");
		String token = (String) mapData.get("token");

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			try {
				JSONObject body = new JSONObject();
				UCResult resuelt = null;
				body.put("TOKEN", token);
				body.put("userid", userId);
				
				resuelt = BaseAction.requeryUC("UAC_USER_INFO", body);
				if (resuelt.code.equals("1")) {
					stsMap.put("sts", "1");
					stsMap.put("userName", resuelt.body.getJSONObject("user").getString("truename"));
				
					stsMap.put("userContact", resuelt.body.getJSONObject("user").getString("phone"));
					stsMap.put("usertype", resuelt.body.getJSONObject("user").getString("role"));
					stsMap.put("userCompany", resuelt.body.getJSONObject("user").getString("userCompany"));
					stsMap.put("group", resuelt.body.getJSONObject("user").getString("groupID"));
					stsMap.put("groupName", resuelt.body.getJSONObject("user").getString("orgName"));
			
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
					return null;
				} else {
					stsMap.put("sts", "1");
					stsMap.put("msg", "uc 返回错误：" + resuelt.code);
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
					return null;
				}
			} catch (JSONException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	// 设置考勤围栏接口
	@Execute(validator = false)
	public String saveUserArea() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;

		String userId = (String) mapData.get("userId");
		String seatId = (String) mapData.get("seatId");
		String leftTopLon = (String) mapData.get("leftTopLon");
		String leftToplat = (String) mapData.get("leftToplat");
		String rightBottomLon = (String) mapData.get("rightBottomLon");
		String rightBottomlat = (String) mapData.get("rightBottomlat");
		String startTime = (String) mapData.get("startTime");
		String endTime = (String) mapData.get("endTime");

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(seatId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "seatId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(leftTopLon)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "leftTopLon不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(leftToplat)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "leftToplat不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(rightBottomLon)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "rightBottomLon不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(rightBottomlat)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "rightBottomlat不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(startTime)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "startTime不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(endTime)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "endTime不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			PiccUserArea piccUserArea = piccUserAreaService.findByUserId(userId);
			Timestamp dbTimeStamp = dbTimeService.getDbTimeStamp();
			if (null == piccUserArea) {
				PiccUserArea piccUserArea2 = new PiccUserArea();
				piccUserArea2.id = UUID.randomUUID().toString().replace("-", "");
				piccUserArea2.userId = userId;
				piccUserArea2.createUser = seatId;
				piccUserArea2.leftTopLon = leftTopLon;
				piccUserArea2.leftTopLat = leftToplat;
				piccUserArea2.rightBottomLon = rightBottomLon;
				piccUserArea2.rightBottomLat = rightBottomlat;
				piccUserArea2.startTime = Timestamp.valueOf(startTime);
				piccUserArea2.endTime = Timestamp.valueOf(endTime);
				piccUserArea2.createTime = dbTimeStamp;
				piccUserAreaService.insert(piccUserArea2);
				stsMap.put("sts", "0");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			} else {
				piccUserArea.userId = userId;
				piccUserArea.updateUser = seatId;
				piccUserArea.leftTopLon = leftTopLon;
				piccUserArea.leftTopLat = leftToplat;
				piccUserArea.rightBottomLon = rightBottomLon;
				piccUserArea.rightBottomLat = rightBottomlat;
				piccUserArea.startTime = Timestamp.valueOf(startTime);
				piccUserArea.endTime = Timestamp.valueOf(endTime);
				piccUserArea.updateTime = dbTimeStamp;
				piccUserAreaService.update(piccUserArea);
				stsMap.put("sts", "0");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}

	// 上传经纬度接口
	@Execute(validator = false)
	public String updateLocation() {
		Gson gson = new Gson();
		StringBuffer indata = StreamUtil.getRequestBody(req);
		Map<String, String> stsMap = new HashMap<String, String>();

		Map<String, String> mapData = gson.fromJson(indata.toString(), Map.class);
		if (mapData == null)
			return null;

		String userId = (String) mapData.get("userId");
		String lon = (String) mapData.get("lon");
		String lat = (String) mapData.get("lat");
		String speed = (String) mapData.get("speed");
		String direction = (String) mapData.get("direction");
		String height = (String) mapData.get("height");
		String radius = (String) mapData.get("radius");
		String locTime = (String) mapData.get("locTime");

		try {
			rep.setCharacterEncoding("utf-8");
			if (StringUtils.isBlank(userId)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "userId不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			if (StringUtils.isBlank(lon)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "lon不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(lat)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "lat不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}
			if (StringUtils.isBlank(locTime)) {
				stsMap.put("sts", "1");
				stsMap.put("msg", "locTime不能为空");
				rep.getWriter().println(gson.toJson(stsMap));
				rep.getWriter().flush();
				return null;
			}

			String url = "http://yingyan.baidu.com/api/v3/track/addpoint";
			HttpClient hc = new HttpClient();
			PostMethod pm = new PostMethod(url);

			pm.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");

			pm.setParameter("ak", Constants.ak);
			pm.setParameter("service_id", Constants.service_id);
			pm.setParameter("entity_name", userId);

			pm.setParameter("latitude", lat);
			pm.setParameter("longitude", lon);

			SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

			long date = 0;
			try {
				date = formatter.parse(locTime).getTime() / 1000l;
			} catch (ParseException e1) {
				e1.printStackTrace();
			}

			String aa = date + "";
			pm.setParameter("loc_time", aa);
			pm.setParameter("coord_type_input", "bd09ll");
			if (!StringUtils.isBlank(speed)) {
				pm.setParameter("speed", speed);
			}
			if (!StringUtils.isBlank(direction)) {
				pm.setParameter("direction", direction);
			}
			if (!StringUtils.isBlank(height)) {
				pm.setParameter("height", height);
			}
			if (!StringUtils.isBlank(radius)) {
				pm.setParameter("radius", radius);
			}

			try {
				hc.executeMethod(pm);
				String ret = pm.getResponseBodyAsString();

				BaiduAddPointResult rresult = gson.fromJson(ret, BaiduAddPointResult.class);

				if (rresult.status == 0) {
					PiccUserLocation piccUserLocation = new PiccUserLocation();
					piccUserLocation.id = UUID.randomUUID().toString().replace("-", "");
					piccUserLocation.userId = userId;
					piccUserLocation.lon = lon;
					piccUserLocation.lat = lat;
					piccUserLocation.speed = speed;
					piccUserLocation.direction = direction;
					piccUserLocation.height = height;
					piccUserLocation.radius = radius;

					piccUserLocation.locTime = locTime;
					String dateString = formatter.format(dbTimeService.getDbTimeStamp());
					piccUserLocation.updateTime = dateString;
					piccUserLocationService.insert(piccUserLocation);
					stsMap.put("sts", "0");
					rep.getWriter().println(gson.toJson(stsMap));
					rep.getWriter().flush();
				} else {
					if (StringUtils.isBlank(locTime)) {
						stsMap.put("sts", "1");
						stsMap.put("msg", "百度添加失败，可能userid没有创建");
						rep.getWriter().println(gson.toJson(stsMap));
						rep.getWriter().flush();
						return null;
					}
				}
				System.out.println(ret);

			} catch (HttpException e) {

				e.printStackTrace();
			} catch (IOException e) {

				e.printStackTrace();
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}



}